package com.chalk.controller;

import com.chalk.common.util.Result;
import com.chalk.util.ImgUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/v1/upload")
public class UploadController {

    @Value("${upload.dir}")
    String dir;

    @Value("${ip.addr}")
    String addr;

    /**
     * 上传文件
     * @param file
     * @return
     */

    @PostMapping("uploadFile")@ApiOperation(value = "上传文件", notes = "上传文件", response = Result.class)
    public Result uploadFile(@RequestParam(value = "file") MultipartFile file)throws IOException {
        //需要返回的消息
        Map<String,Object> data = new HashMap<>();
        if( !file.isEmpty()) {

            //上传目录
            String uploadPath = dir + "/img/";
            //验证图片后缀
            String suffix= ImgUtil.splitImg(file.getOriginalFilename());
            //图片名称
            String imgName=System.currentTimeMillis() + "." + suffix;
            if(ImgUtil.checkImg(suffix)) {
                File upFile = new File(uploadPath ,imgName);
                if (!upFile.exists()) {
                    upFile.createNewFile();
                } else {
                    upFile.delete();
                }
                System.out.println(upFile.getAbsoluteFile());
                file.transferTo(upFile.getAbsoluteFile());
                data.put("msg","上传成功");
                data.put("imgUrl",addr+"upload/img/"+imgName);


            }
            else {
                data.put("msg","图片格式错误，请上传jpg/png/gif格式的图片");
            }



        }else {
            data.put("msg","图片不能为空！");
        }

        return  Result.success(data);

    }

}
